package com.tom.demo.service.async.impl;

import cn.hutool.core.lang.Snowflake;
import com.tom.demo.common.esEntity.SysLogDocIndex;
import com.tom.demo.esRepository.SysLogRepository;
import com.tom.demo.service.async.AsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * 异步执行服务
 */
@Slf4j
@Service
public class AsyncServiceImpl implements AsyncService {
    @Resource
    private SysLogRepository sysLogRepository;
    @Resource
    private Snowflake snowflake;
    /**
     * 异步保存日志
     * @param sysLogDocIndex
     */
    @Override
    @Async(value = "springAsyncTaskExecutor")
    public void saveLogAsync(SysLogDocIndex sysLogDocIndex,Throwable throwable) {
        try {
            Optional.ofNullable(sysLogDocIndex).ifPresent(sysLogDoc -> {
                sysLogDoc.setId(snowflake.nextIdStr());
                sysLogRepository.save(sysLogDoc);
                log.debug("异步保存操作日志成功 id={}", sysLogDocIndex.getId());
            });
        } catch (Exception e) {
            // 必须捕获并记录，不能抛到线程池外（会被吞掉但可由 AsyncUncaughtExceptionHandler 处理）
            log.error("异步保存操作日志失败 id={} err={}", sysLogDocIndex.getId(), e.getMessage(), e);
            // 可在这里做二次持久化：写入本地文件/DB/告警队列，避免丢失
            Optional.ofNullable(throwable).ifPresent(throwableObject -> {
                log.error("异步保存操作日志失败 id={} err={}", sysLogDocIndex.getId(), throwableObject.getMessage(), throwableObject);
            });

        }
    }
}
